package com.morningstar.common.dao.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

import static com.morningstar.common.dao.entity.EntityConstants.*;

/**
 * @author yanglianshan
 */
@Slf4j
@Component
public class MyBatisPlusConfig implements MetaObjectHandler {

    @Resource
    private LogonUser logonUser;

    /**
     * 配置mybatis plus 拦截器
     *
     * @return mybatis 配置
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setOptimizeJoin(true);
        paginationInnerInterceptor.setDbType(DbType.MYSQL);
        paginationInnerInterceptor.setOverflow(true);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor = new OptimisticLockerInnerInterceptor();
        interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor);
        return interceptor;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        if (logonUser != null) {
            log.info("CREATE_BY {}", logonUser.getLogonUserId());
            this.strictInsertFill(metaObject, CREATE_BY, Long.class, logonUser.getLogonUserId());
        }
        LocalDateTime date = LocalDateTime.now();
        this.strictInsertFill(metaObject, CREATE_TIME, LocalDateTime.class, date);
        this.strictInsertFill(metaObject, DEL_FLAG, String.class, DEL_FLAG_NORMAL);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (logonUser != null) {
            log.info("UPDATE_BY {}", logonUser.getLogonUserId());
            this.strictUpdateFill(metaObject, UPDATE_BY, Long.class, logonUser.getLogonUserId());
        }
        this.strictUpdateFill(metaObject, UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
    }
}
